package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;

@Slf4j
@Configuration
/**
 * 条件注解，意思是环境中必须有ly.auth开头的属性，属性名称必须叫clientId和secret，
 * 确保使用者会在yml中配置clientId和secret时，当前配置才会生效。
 * 为了让这个配置被SpringBoot加载，我们需要在ly-auth-api的resources目录中
 * 创建一个文件夹：META-INF，
 * 然后创建一个文件：spring.factories
 * 加载时候  会发起feign请求  authClient.getSecretKey
 */
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
@EnableConfigurationProperties(ClientProperties.class)
public class AuthConfiguration {

    @Autowired
    private AuthClient authClient;
    @Autowired
    private ClientProperties properties;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    @Primary
    public JwtUtils jwtUtils(){
        try {
            // 查询秘钥
            String key = authClient.getSecretKey(properties.getClientId(), properties.getSecret());
            // 创建JwtUtils
            JwtUtils jwtUtils = new JwtUtils(key,redisTemplate);
            log.info("秘钥加载成功:{}",key);
            return jwtUtils;
        } catch (Exception e) {
            log.error("初始化JwtUtils失败，{}", e.getMessage());
            throw e;
        }
    }
}
